<?php
namespace addons\paotui\service;

use app\admin\model\paotui\Posterextract;
use app\admin\model\paotui\PosterMoneyLog;

use think\Db;

class Poster{
    public $error;

    /**
     * 获取服务数量
     */
    public function getServiceNum($poster_id){
        $postModel = new \app\admin\model\paotui\Post();
        return $postModel->where(['status'=>5,'poster_id'=>$poster_id])->count();
    }

    /**
     * 获取可提现金额
     */
    public function getAllowExtractMoney($poster_id){
        $posterModel = new \app\admin\model\paotui\Poster();
        $posterInfo = $posterModel->where(['id'=>$poster_id])->find();
        $totalMoney = empty($posterInfo['money'])?0:$posterInfo['money'];

        //获取正在申请提现的佣金
        $posterExtractModel = new Posterextract();
        $extractingPrice = $posterExtractModel->where(['status'=>0,'poster_id'=>$poster_id])->sum('extract_price');
        $extractingPrice = empty($extractingPrice)?0:$extractingPrice;
        $money = bcsub($totalMoney,$extractingPrice,2);
        $money = $money<=0?0:$money;

        return $money;
    }

    /**
     * 获取快递员今日收入
     */
    public function getTodayMoney($poster_id){
        $posterMoneyLog = new PosterMoneyLog();
        //获取今日开始结束时间戳
        $begin_time = strtotime(date("Y-m-d"));
        $end_time = bcadd($begin_time,60*60*24-1);

        $money = $posterMoneyLog->where(['poster_id'=>$poster_id,'type'=>'order','createtime'=>['between',[$begin_time,$end_time]]])->sum("money");

        return empty($money)?0:$money;
    }

    /**
     * 获取本周收益
     * @param $poster_id
     * @return float|int|string
     */
    public function getWeekMoney($poster_id){

        //当前日期
        $sdefaultDate = date("Y-m-d");
        //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $first=1;
        //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $w=date('w',strtotime($sdefaultDate));
        //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $week_start=strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days');

        //本周结束日期
        $week_end=strtotime(" +7 days -1 seconds",$week_start);

        $posterMoneyLog = new PosterMoneyLog();
        $money = $posterMoneyLog->where(['poster_id'=>$poster_id,'type'=>'order','createtime'=>['between',[$week_start,$week_end]]])->sum("money");

        return empty($money)?0:$money;
    }

    /**
     * 获取今日快递员已完成接单数量
     */
    public function getTodayCompletePostNum($poster_id){

        $begin_time = strtotime(date("Y-m-d"));
        $end_time = bcadd($begin_time,60*60*24-1);

        $postModel = new \app\admin\model\paotui\Post();
        return $postModel->where(['status'=>5,'completetime'=>['between',[$begin_time,$end_time]]])->where("FIND_IN_SET($poster_id,poster_id)")->count();
    }

    /**
     * 获取佣金记录列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getMoneyLogList($where,$page,$limit){
        $model = new PosterMoneyLog();
        $count = $model
            ->alias("money_log")
            ->join("paotui_post post","money_log.source_id = post.id and (money_log.type = 'order' || money_log.type = 'spread')",'left')
            ->where($where)->count();
        if($page){
            $data = $model
                ->field("money_log.money,money_log.type,money_log.memo,money_log.createtime,post.order_no")
                ->alias("money_log")
                ->join("paotui_post post","money_log.source_id = post.id and (money_log.type = 'order' || money_log.type = 'spread')",'left')
                ->where($where)->page($page,$limit)->order("money_log.id desc")->select();
        }else{
            $data = $model
                ->field("money_log.money,money_log.type,money_log.memo,money_log.createtime,post.order_no")
                ->alias("money_log")
                ->join("paotui_post post","money_log.source_id = post.id and (money_log.type = 'order' || money_log.type = 'spread')",'left')
                ->where($where)->order("money_log.id desc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }

    /**
     * 获取佣金提现列表
     * @param $page
     * @param $limit
     * @throws \think\Exception
     */
    public function getExtractList($where,$page,$limit){
        $model = new Posterextract();
        $count = $model->where($where)->count();
        if($page){
            $data = $model->where($where)->page($page,$limit)->order("id desc")->select();
        }else{
            $data = $model->where($where)->order("id desc")->select();
        }

        return ['total'=>$count,'data'=>$data];
    }

    //佣金分配
    public function brokerage($order_no){
       
        $postModel = new \app\admin\model\paotui\Post();
        $postInfo = $postModel->where(['status'=>5,'order_no'=>$order_no])->find();
        if(empty($postInfo)){
            $this->error = "快递单状态异常";
            return false;
        }
         
        //验证进度
        if($postInfo['status'] != 5){
            $this->error = "当前订单状态异常";
            return false;
        }
        
        //验证是否已经分配过佣金
        $posterMoneyLogModel = new PosterMoneyLog();
        if($posterMoneyLogModel->where(['type'=>'order','source_id'=>$postInfo['id'],'memo'=>'服务收入'])->find()){
            $this->error = "当前订单已经完成";
            return false;
        }
        //获取当前可分配佣金金额
        Db::startTrans();

        //获取当前快递员的当前金额
        $posterModel = new \app\admin\model\paotui\Poster();
        $posterInfo = $posterModel->where(['id'=>$postInfo['poster_id'],'status'=>1])->find();
        if(empty($posterInfo)){
            return true;
        }

        //获取佣金
        if($postInfo['type'] ==2){
            $brokerage = $postInfo['brokerage'];
        
        }else{
            $brokerage = Post::poster_brokerage($postInfo['brokerage'],$postInfo['type'],$posterInfo['poster_type'],$posterInfo['brokerage_type'],$posterInfo['brokerage_scale']);
        }
        if($brokerage > $postInfo['brokerage']){
            $this->error = "数据异常";
            return false;
        }
		
		//20240825 masks 处理减分销商佣金 开始
		$comrule=db('shopro_commission_level')->where('level',1)->find();
		$cosrule=json_decode($comrule['commission_rules'],1);
		$amount=$cosrule['fee_4'];
		$brokerage=$brokerage-$amount;
		if($brokerage<=0){
            $this->error = "数据异常1";
            return false;
		}
		//20240825 masks 处理减分销商佣金 结束
        
        $after = bcadd($posterInfo['money'],$brokerage,2);
        $posterMoneyLogModel = new PosterMoneyLog();
        if(!$posterMoneyLogModel->save([
            'poster_id'=>$posterInfo['id'],
            'type'=>'order',
            'source_id'=>$postInfo['id'],
            'money'=>$brokerage,
            'before'=>$posterInfo['money'],
            'after'=>$after,
            'memo'=>'服务收入'
        ])){
            Db::rollback();
            return false;
        }
        if(!$posterInfo->save(['money'=>$after])){
            Db::rollback();
            return false;
        }

        Db::commit();
        return true;
    }
}